package com.duke.duke.javaagent.base01.example.command;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryManagerMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.util.List;

/**
 * 内存命令 获取运行时内存使用情况  （堆内存、非堆内存）
 * @author gjy
 * @create 2024-11-22 3:44 PM
 */
public class MemoryCommand {
    //打印所有的内存信息
    public static void printMemoryInfo(){
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        System.out.println("堆内存使用：");
        //堆内存使用情况
        memoryPoolMXBeans.stream().filter(bean -> bean.getType().equals(MemoryType.HEAP))
                .forEach(bean -> {

                    StringBuffer sb = new StringBuffer();
                    sb.append("name");
                    sb.append(bean.getName());
                    sb.append(" max: ");
                    sb.append(bean.getUsage().getMax());
                    sb.append(" used: ");
                    sb.append(bean.getUsage().getUsed());
                    System.out.println(sb);
                });

        System.out.println("非堆内存使用：");
        //非堆内存使用情况
        memoryPoolMXBeans.stream().filter(bean -> bean.getType().equals(MemoryType.NON_HEAP))
                .forEach(bean -> {

                    StringBuffer sb = new StringBuffer();
                    sb.append("name");
                    sb.append(bean.getName());
                    sb.append(" max: ");
                    sb.append(bean.getUsage().getMax());
                    sb.append(" used: ");
                    sb.append(bean.getUsage().getUsed());
                    System.out.println(sb);
                });
    }

}
